package com.wei.service.impl;

import com.wei.dao.Page;
import com.wei.dao.read.WechatAuthReadMapper;
import com.wei.dao.write.WechatAuthOptMapper;
import com.wei.entity.WechatAuth;
import com.wei.service.IWechatAuthService;
import com.wei.service.wrapper.RedisCacheWrapper;
import com.wei.utils.ExceptionUtils;
import com.wei.utils.Stringutils;
import com.wei.utils.random.RandomUtils;
import com.wei.utils.wechat.Code2Session;
import com.wei.utils.wechat.TencentCloudSendSms;
import com.wei.utils.wechat.WeChatRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class WechatAuthServiceImpl implements IWechatAuthService {
    @Autowired
    private WechatAuthOptMapper wechatAuthOptMapper;
    @Autowired
    private WechatAuthReadMapper wechatAuthReadMapper;
    @Autowired
    private RedisCacheWrapper redisCacheWrapper;


    public boolean insert(WechatAuth wechatAuth) {
        return wechatAuthOptMapper.insert(wechatAuth) > 0;
    }

    public boolean update(WechatAuth wechatAuth) {
        return wechatAuthOptMapper.update(wechatAuth) > 0;
    }

    public boolean delete(Integer id) {
        //抛出未实现异常
        throw new UnsupportedOperationException();
    }

    public boolean batchSava(List<WechatAuth> wechatAuthList) {
        return wechatAuthOptMapper.batchSava(wechatAuthList) > 0;
    }


    public WechatAuth getById(String id) {
        return wechatAuthReadMapper.getById(id);
    }

    public Integer totalCount() {
        return wechatAuthReadMapper.totalCount();
    }

    public List<WechatAuth> getAll(Page<WechatAuth> page) {
        return wechatAuthReadMapper.getAll(page);
    }

    public  String getToken(String code, String appid, String secret){
        WechatAuth wechatAuth = null;
        Code2Session code2Session = WeChatRequest.login(code, appid, secret);
        if (!Stringutils.isEmptyOrWhiteSpace(code2Session.getOpenid())) {
            // 根据appid获取WechatAuth
            wechatAuth = getById(code2Session.getOpenid());
            if (wechatAuth != null && !Stringutils.isEmptyOrWhiteSpace(wechatAuth.getOpenId())) {
                return wechatAuth.getToken();
            }
        }
        if (!Stringutils.isEmptyOrWhiteSpace(code2Session.getOpenid())) {
            String random = UUID.randomUUID().toString().replaceAll("-", "").substring(8,24);

            wechatAuth = new WechatAuth();
            wechatAuth.setType("01");
            wechatAuth.setToken(random);
            wechatAuth.setOpenId(code2Session.getOpenid());
            wechatAuth.setSessionKey(code2Session.getSession_key());
            wechatAuth.setModDt(new Date());
            wechatAuth.setUnionId(code2Session.getUnionid());
            insert(wechatAuth);

            return random;
        } else {
           throw  ExceptionUtils.mpe("错误编码:%s  错误信息:%s",code2Session.getErrcode(),code2Session.getErrmsg());
        }
    }

    public boolean sendVerifyCode(String phoneNumber){
        long expire = redisCacheWrapper.getExpireTime(phoneNumber);

        if(expire>=2*60){
            throw ExceptionUtils.mpeValidator("%s", "操作过于频繁!");
        }

        String random = RandomUtils.random(6);
        redisCacheWrapper.put(phoneNumber,random,3*60);//3分钟

        TencentCloudSendSms.SendMessage(phoneNumber, random+",3");
        return true;
    }

    public boolean verifyCode(String phoneNumber,String verifyCode){
        if(!phoneNumber.startsWith("+86")){
            phoneNumber = "+86"+phoneNumber;
        }
        if(!redisCacheWrapper.hasKey(phoneNumber)){
            return false;
        }
        String code = redisCacheWrapper.get(phoneNumber,String.class);
        if(verifyCode.equals(code)){
            return true;
        }
        return false;
    }
}
